﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using NDatabase;
using Group3.MediaTool.Interface;

namespace Group3.MediaTool.Provider
{
    /// <summary>
    /// @Version 1.0
    /// @Author: P. Senjic
    /// @Comment:
    ///     The NDatabaseProvider is a specific Implementation of the abstract DataStoreProvider.
    ///     It uses the NDatabase, a codeplex object database http://ndatabase.codeplex.com/
    ///     The FileExtension for the Storeproterty must be set as ".db"
    /// </summary>
    public class NDatabaseProvider : DataStoreProvider
    {
        #region override DataStoreProvider
        public override bool ExecuteAction<T>(Action<T> action, T parameter)
        {
            return base.ExecuteAction<T>(action, parameter);
        }

        public override IEnumerable<IObjectRelationModel> GetDataFromStore<T>()
        {
            //Open a Datastore
            //i.e.: d:\test.db
            using (var odb = NDatabase.OdbFactory.Open(Path.Combine(this.Connect, this.Store)))
            {
                try
                {
                    var result =  (from c in odb.AsQueryable<T>()
                                select (IObjectRelationModel)c).ToList();
                    return result;

                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        public override IEnumerable<IObjectRelationModel> GetDataFromStore<T>(Predicate<T> filterstmt)
        {
            using (var odb = NDatabase.OdbFactory.Open(Path.Combine(this.Connect, this.Store)))
            {
                try
                {
                    if (filterstmt == null)
                        return GetDataFromStore<IObjectRelationModel>();
                    var result =  (from c in odb.AsQueryable<T>()
                            where filterstmt(c)
                            select (IObjectRelationModel)c).ToList();
                    return result;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }

        public override bool SaveChanges(Interface.IObjectRelationModel orm)
        {
            using (var odb = NDatabase.OdbFactory.Open(Path.Combine(this.Connect, this.Store)))
            {
                try
                {
                    
                    odb.Store<Interface.IObjectRelationModel>(orm);
                    odb.Commit();
                    return true;
                }
                catch (Exception)
                {
                    odb.Rollback();
                    return false;
                }
            }
        }

        #endregion
    }
}
